<?php

/*
	This file is part of Mandragon.

    Mandragon is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Mandragon is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Mandragon.  If not, see <http://www.gnu.org/licenses/>.
*/

class PollPage {

	private $alerter;
	private $item_functions;
	private $db_access;
	private $access;
	private $toolbox;
	
	public function __construct() {
		$this->alerter = new Alerter();
		$this->item_functions = new ItemFunctions();
		$this->db_access = new DbAccessor();
		$this->access = new AccessManager();
		$this->creator = new FormCreator();
		$this->toolbox = new Toolbox();
	}

	/**
	* adds extra access checks, dependent on page state
	*/
	function page_inc_check_access($page) {
		$this->item_functions->item_page_inc_check_access($page);
	}

	/**
	* appropriate page action interpretations
	*/
	function page_inc_execute_action($action) {
		switch($action) {
			case "change_vote": //TODO: remove fallthrough
			case "show_results":
				break;
			default:
				$this->item_functions->item_page_inc_execute_action($action, 'poll');
				break;
		}
	}

	/**
	* execute page logic
	*/
	function page_inc_execute($page) {
		global $has_voted;
		$CONTENT = array();

		$where = "ITEM.item_id = {$page->id} AND 
				  ITEM.item_id = POLL.item_id AND 
				  ITEM.author = M1.user_id AND 
				  ITEM.editor = M2.user_id";

		$sql = $this->db_access->db_query_select(
				array(
						array('*'),
						array('body'),
						array(),
						"M1.nick AS nick_author, M2.nick AS nick_editor"), 
				array('ITEM','POLL','MEMBER AS M1, MEMBER AS M2', 'DUMMY'), 
				$where);
		$sqlresult = $this->db_access->db_do_query($sql);

		if ($this->db_access->db_num_rows($sqlresult) !=1) {
			errorpage(404);
		}

		$CONTENT['poll'] = $this->db_access->db_fetch_array($sqlresult);

		if ($CONTENT['poll']['deleted']) {
			errorpage(404);
		}

		$CONTENT['title'] = $CONTENT['poll']['title'];
		$CONTENT['owner'] = $CONTENT['poll']['author'];

		$ipstring = $_SERVER["REMOTE_ADDR"]." - ".$_SERVER["HTTP_X_FORWARDED_FOR"];
		$anonymous = md5("{$page->id} {$_SESSION['user_id']} $ipstring");

		if ($_COOKIE[$CONFIG['cookie_name'] . 'poll' . $page->id])
			$where = "anonymous_id = '{$_COOKIE['mdgpoll' . $page->id]}'";
		else
			$where = "anonymous_id = '$anonymous'";
		if ($_SESSION['user_id'])
			$where = "(($where) OR (user_id = {$_SESSION['user_id']}))";
		$where = "$where AND item_id = {$page->id}";
		$sql = $this->db_access->db_query_select(array(array('*')), array("POLL_VOTE"), $where);
		$sqlresult = $this->db_access->db_do_query($sql);
		if ($this->db_access->db_num_rows($sqlresult) > 0) {
			$has_voted = 1;
			$CONTENT['poll']['uservote'] = $this->db_access->db_fetch_array($sqlresult);
			if ($_GET['action'] != "change_vote") {
				$this->toolbox->add_action($page, "change_vote", "url-action", "change_vote");
			}
		} elseif ($_GET['action'] != "show_poll_results") {
			$this->toolbox->add_action("show_poll_results", "url-action", "show_results");
		}
			
		if ($_POST['submitted'] and $_POST['voting']) {

			check_access("VOTE");
			
			if ($has_voted) {
				$sql = $this->db_access->db_query_update(array('answer_id'), array($_POST['choice']), "POLL_VOTE", "vote_id = {$CONTENT['poll']['uservote']['vote_id']}");
			} else {
				$sql = $this->db_access->db_query_insert(array('item_id', 'answer_id', 'user_id', 'anonymous_id'), array($page->id, $_POST['choice'], $_SESSION['user_id'] ? $_SESSION['user_id'] : "NULL", db_sqlize($anonymous)), "POLL_VOTE", "vote_id = {$CONTENT['poll']['uservote']['vote_id']}");
			}
			
			$this->db_access->db_do_query($sql);
			
			setcookie($_COOKIE[$CONFIG['cookie_name'] . 'poll' . $page->id], $anonymous, time() + 86400000, "/");
				
			$has_voted = 1;
			$this->alerter->add_alert("Uw stem is geregistreerd");
		}

		$sql = $this->db_access->db_query_select(array(array(), "POLL_ANSWER.answer_id, POLL_ANSWER.answer, COUNT(vote_id) AS votes"), array("POLL_ANSWER LEFT JOIN POLL_VOTE ON POLL_ANSWER.answer_id = POLL_VOTE.answer_id", "DUMMY"), "POLL_ANSWER.item_id = {$page->id}", "", "", "POLL_ANSWER.answer_id");
		$sqlresult = $this->db_access->db_do_query($sql);
		$CONTENT['poll']['answers'] = array();
		while ($a = $this->db_access->db_fetch_array($sqlresult)) {
			array_unshift($CONTENT['poll']['answers'], $a);
		}

		if ((($_GET['action'] == 'change_vote') || !$has_voted) && $this->access->has_access("VOTE")) {
			
			$as = $CONTENT['poll']['answers'];
			$keys = array();
			$vals = array();
			while ($a = array_shift($as)) {
				array_unshift($keys, $a['answer_id']);
				array_unshift($vals, $a['answer']);
			}
			$inputs = array($this->creator->input_hidden("voting", 1), $this->creator->input_radio("Stem", "choice", $keys, $vals, $CONTENT['poll']['uservote']['answer_id']));
			$CONTENT['poll']['form'] = $this->creator->create("voteform", $inputs, "{$page->dir_path}/{$page->id}.poll");		
		}
			
		$page->content = $CONTENT;

		$this->item_functions->item_page_inc_execute($page, 'poll');
	}


	/**
	* dress up page content using skin stuff
	*/
	function page_inc_dress($page) {
		global $has_voted;

		$this->item_functions->item_page_inc_dress_before($page);

		if ($has_voted || ($_GET['action'] == 'show_results') || !$this->access->has_access("VOTE")) {
			$answers = $page->content['poll']['answers'];
		}

		if ((!$has_voted || ($_GET['action'] == 'change_vote')) && $this->access->has_access("VOTE")) {
			$form = $page->content['poll']['form'];
		}

		$page->content['poll']['body'] = $this->db_access->db_desqlize($page->content['poll']['body']);
		print_poll($page, $page->content['poll'], $answers, $form);
			
		$this->item_functions->item_page_inc_dress_after($page);
	}
}

?>
